load(file = "data/intermediate/prom_sum.rda")
# load(file = "data/intermediate/promise.index.rda")
library(haven)
library(reshape2)
library(mellonMisc)
library(dplyr)
library(glmnet)
library(ridge)
library(brms)
library(readxl)
library(metRology)
library(survey)
library(plm)
library(plotly)
library(ggplot2)
library(readr)
# library(cmdstanr)


source("scripts/promise_functions.R")
set.seed(23824)
fit <-  bf(import|weights(weight) ~  
                     (1 |p|mm(g1, g2, g3, g4)) +
                     (1 |q|mm(mii1, mii2, mii3, mii4)) +
                     (1| id) + (1|page))

fit.approv <-  bf(approval|weights(weight) ~   
                            (1 |p|mm(g1, g2, g3, g4)) +
                            (1 |q|mm(mii1, mii2, mii3, mii4)) +
                            (1|id) + (1|page))


get_prior(formula = fit + fit.approv, data = prom.sum)
fit.all <- brm(fit + fit.approv, data = prom.sum, 
    cores = 4, prior = c(set_prior('exponential(0.7)', class = "sd", resp = "approval"),
                         set_prior('exponential(0.7)', class = "sd", resp = "import"),
                         # set_prior('normal(0, 3)', class = "b", resp = "approval"),
                         # set_prior('normal(0, 3)', class = "b", resp = "import"),
                         set_prior('lkj(2)', class = "cor")) ,
    seed = 2398423)
summary(fit.all)

# 
fit.c <-  bf(import|weights(weight) ~  votecon + 
             (1 +votecon|p|mm(g1, g2, g3, g4)) +
             (1 +votecon|q|mm(mii1, mii2, mii3, mii4)) +
             (1| id) + (1|page))

fit.approv.c <-  bf(approval|weights(weight) ~ votecon + 
                    (1 +votecon|p|mm(g1, g2, g3, g4)) +
                    (1 +votecon|q|mm(mii1, mii2, mii3, mii4))
                    +
                    (1|id) + (1|page))

get_prior(formula = fit.c + fit.approv.c, data = prom.sum)
fit.con <- brm(fit.c + fit.approv.c, data = prom.sum, 
               cores = 4, prior = c(set_prior('exponential(0.7)', class = "sd", resp = "approval"),
                                    set_prior('exponential(0.7)', class = "sd", resp = "import"),
                                    set_prior('lkj(2)', class = "cor") ),
               seed = 213842, iter = 4000, warmup = 2000)

summary(fit.con)

save.image(file = "data/intermediate/models_multivariate.Rdata")
